package gspushmq.v1.subscribe.send;

import java.util.Enumeration;
import java.util.Iterator;

import org.java_websocket.WebSocket;

import gspushmq.model.DataMessage;
import gspushmq.model.Message;
import gspushmq.model.MessageType;
import gspushmq.model.User;
import gspushmq.util.GGLogger;
import gspushmq.v1.produce.GGDataStorage;
import gspushmq.v1.subscribe.GGSubscribe;
import gspushmq.v1.subscribe.send.core.GGSend;

/**
 *
 * 推送数据给前端
 * @version 1.0
 * @since JDK1.7
 * @author yutao
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2016 SunTime Co'Ltd Inc.All rights reserved.
 * @date 2018年11月15日下午4:51:17
 */
public class GGSendSysTags extends GGSend {

	
	/**
	 *  推送系统消息
	 * @author yutao
	 * @date 2018年11月15日下午5:29:41
	 */
	private void handlerSys() {
		
		while(true){
				
			if(GGSubscribe.activeQueue.isEmpty()){
				try {
					Thread.sleep(500);
					continue;
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			Iterator<MessageType> iterator = GGSubscribe.activeQueue.iterator();
//			synchronized (iterator) {
				while(iterator.hasNext()){
					MessageType messType = iterator.next();
					//需要推送的数据
					DataMessage dataMessage = GGDataStorage.MessageMap.get(messType);
					if(dataMessage == null || dataMessage.getContent() == null){
						continue;
					}
					
					int i = 0;
					try {
						//该类型下的用户集合
//						
						Enumeration<WebSocket> wsList = GGSubscribe.wstUser.keys();
						if(wsList == null){ //说明此时没有人订阅
							continue;
						}
						int y = 0 ;
						while (wsList.hasMoreElements()) {
							WebSocket wst = wsList.nextElement();
							i++;
							if(wst.isOpen()){
								User user = GGSubscribe.wstUser.get(wst);
								Message mess = new Message();
								mess.setAccount_id(user.getAccountId());
								mess.setAccount_name(user.getAccountName());
								mess.setRequest_id("msg_private_tags");
								mess.setProduct_line(user.getProductLine());
								mess.setMq_type("sys");
								mess.setMq_sub_type("tags");
								//用户订阅的消息集合
								sendWebSocket(mess, wst, dataMessage);
								y++;
							}
						}
						GGLogger.info(GGSendSysTags.class, "tags 20190123 send  " + y);
					} catch (Exception e) {
						// TODO: handle exception
					} finally {
						GGLogger.info(GGSendSysTags.class, "tags 20190123 intI " + i);
						GGDataStorage.MessageMap.remove(messType);
						GGSubscribe.activeQueue.remove(messType);
					}
					GGDataStorage.MessageMap.remove(messType);
					GGSubscribe.activeQueue.remove(messType);
				}
//			}
		}
	}

	
	@Override
	public void handler() {
		handlerSys();
	}
}
